package com.leju.common.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @ClassName: Utils
 * @Description: 工具类
 * @author yingjun fan
 * @date 2012-10-29 上午10:24:48
 * @email yingjun@leju.com
 * 
 */
public class Utils {

	private static final String TAG = "leju";
	private static StringBuffer mStrBuf = new StringBuffer();
	private static SimpleDateFormat mFormat = new SimpleDateFormat(
			"dd/MM/yyyy HH:mm:ss");

	/**
	 * 对给定的字符串进行MD5加密
	 * 
	 * @param str
	 * @return
	 */
	public static String MD5(String str) {
		if (!TextUtils.isEmpty(str)) {
			MessageDigest messageDigest = null;
			try {
				messageDigest = MessageDigest.getInstance("MD5");
				messageDigest.reset();
				messageDigest.update(str.getBytes("UTF-8"));
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			byte[] byteArray = messageDigest.digest();
			StringBuffer md5StrBuff = new StringBuffer();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
					md5StrBuff.append("0").append(
							Integer.toHexString(0xFF & byteArray[i]));
				} else {
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
				}
			}
			return md5StrBuff.toString();
		} else {
			return null;
		}
	}

	/**
	 * 打印日志
	 * 
	 * @param msg
	 */
	public static void log(String msg) {
		log(TAG, msg);
	}

	/**
	 * 打印日志
	 * 
	 * @param tag
	 * @param msg
	 */
	public static void log(String tag, String msg) {
		if (!TextUtils.isEmpty(msg) ) {
			Logger.d(tag, msg);
		}
	}

	public static class ConnectNetwork {
		/**
		 * 检测是否有可用的网络
		 * 
		 * @param context
		 * @return
		 */
		public static boolean checkNetwork(final Context context) {
			boolean flag = false;
			ConnectivityManager cwjManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (cwjManager.getActiveNetworkInfo() != null) {
				flag = cwjManager.getActiveNetworkInfo().isAvailable();
			}

			return flag;
		}
	}

	/**
	 * 序列化一个对象
	 * 
	 * @param context
	 * @param fileName
	 * @param object
	 * @return
	 */
	public static synchronized boolean persistObject(Context context,
			String fileName, Object object) {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(context.openFileOutput(fileName,
					Context.MODE_PRIVATE));
			oos.writeObject(object);
			oos.flush();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				oos = null;
			}
		}
		return false;
	}

	/**
	 * 读取一个序列化对象
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static synchronized Object readObject(Context context,
			String fileName) {
		ObjectInputStream ois = null;
		Object object = null;
		try {
			ois = new ObjectInputStream(context.openFileInput(fileName));
			object = ois.readObject();
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				ois = null;
			}
		}
		return object;
	}

	/**
	 * 验证字符串是否为手机号
	 * 
	 * @param mobile
	 * @return
	 */
	public static boolean isMobile(String mobile) {
		if (!TextUtils.isEmpty(mobile)) {
			mobile = mobile.trim();
			String pattern = "^[1]\\d{10}$";
			return mobile.matches(pattern);
		}
		return false;
	}

	/**
	 * 获取外部存储的路径
	 * 
	 * @return null 没有外部存储
	 */
	public static String getExtStorePath() {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			return Environment.getExternalStorageDirectory().getPath();
		}
		return null;
	}

	/**
	 * 显示提示信息
	 * 
	 * @param context
	 * @param msg
	 */
	public static void showMsg(Context context, String msg) {
		if (context != null) {
			Toast.makeText(context, msg, 0).show();
		}
	}

	/**
	 * 显示提示信息
	 * 
	 * @param context
	 * @param resId
	 *            资源id
	 */
	public static void showMsg(Context context, int resId) {
		if (context != null) {
			Toast.makeText(context, resId, 0).show();
		}
	}

	/**
	 * 获取版本name
	 * 
	 * @return 当前应用的版本号(versionName)
	 */
	public static String getVersion(Context context) {
		if (context != null) {
			try {
				PackageManager manager = context.getPackageManager();
				PackageInfo info = manager.getPackageInfo(
						context.getPackageName(), 0);

				return info.versionName;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * 获取版本Code
	 * 
	 * @param context
	 * @return
	 */
	public static int getVersionCode(Context context) {
		if (context != null) {
			try {
				PackageManager manager = context.getPackageManager();
				PackageInfo info = manager.getPackageInfo(
						context.getPackageName(), 0);
				return info.versionCode;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	public static class MapUitls {
		public static void getMapImageView(int width, int height, double x,
				double y, WebView webView) {

			StringBuffer sb = new StringBuffer(
					"http://api.map.baidu.com/staticimage?center=");
			sb.append(x)
					.append(",")
					.append(y)
					.append("&width=")
					.append(width)
					.append("&height=")
					.append(height)
					.append("&zoom=15")
					.append("&markers=")
					.append(x)
					.append(",")
					.append(y)
					.append("&markerStyles=m");
			webView.loadUrl(sb.toString());

		}
	}

	public static class StringUitls {
		/**
		 * 设置textview某一区间显示不同颜色的文字
		 * 
		 * @param startIndex
		 * @param endIndex
		 * @param color
		 * @param textView
		 */
		public static void setTextIntervalColor(int startIndex, int endIndex,
				int color, TextView textView) {
			SpannableString sp = new SpannableString(textView.getText()
					.toString());
			sp.setSpan(new ForegroundColorSpan(color), startIndex, endIndex,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			textView.setText(sp);

		}

		/**
		 * 把包含文本信息的输入流转化为字符串
		 * 
		 * @param inputStream
		 * @return
		 * @throws UnsupportedEncodingException
		 */
		public static String getStringFromInputStream(InputStream inputStream)
				throws UnsupportedEncodingException {
			// BufferedReader br = new BufferedReader(new InputStreamReader(
			// inputStream));

			BufferedReader br = new BufferedReader(new InputStreamReader(
					inputStream, "GB2312")); // 在此设置编码格式，可以消除乱码

			StringBuffer sb = new StringBuffer();
			String line = null;
			try {
				while ((line = br.readLine()) != null) {
					sb.append(line);

				}
			} catch (IOException e) {

				e.printStackTrace();
			} finally {
				try {
					inputStream.close();
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			return sb.toString();
		}

		/**
		 * 判断字符串不为空
		 * 
		 * @param str
		 * @return
		 */
		public static boolean isNotBlank(String str) {
			if (str != null && !"".equals(str) && !".".equals(str)
					&& !"0".equals(str))
				return true;
			return false;
		}

		public static String saveNDecimalPlaces(Float formatNum,
				Integer decimalPoint) {
			StringBuilder sb = new StringBuilder("0.00");
			if (decimalPoint != null) {
				sb.delete(0, sb.length());
				sb.append("0.");
				for (int i = 0; i < decimalPoint; i++) {
					sb.append("0");
				}
			}
			DecimalFormat format = new DecimalFormat(sb.toString());
			return format.format(formatNum);
		}
	}

	public static int dp2px(Context context, int dp) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dp * scale + 0.5);
	}

	/**
	 * zhangsiqi 传入一个ListView，根据他的Item的高度设置他的高度 *
	 * 
	 * @param listView
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	/**
	 * 保存数据到sharePreference
	 * 
	 * @param context
	 * @param key
	 * @return
	 */
	public static void saveStringData(Context context, String projectName,
			String key, String value) {
		SharedPreferences preference = context.getSharedPreferences(
				projectName, Context.MODE_PRIVATE);
		Editor editor = preference.edit();
		editor.putString(key, value);
		editor.commit();
	}

	/**
	 * 从sharePreference中取数据
	 * 
	 * @param context
	 * @param key
	 * @return
	 */
	public static String getStringData(Context context, String projectName,
			String key) {
		SharedPreferences preference = context.getSharedPreferences(
				projectName, Context.MODE_PRIVATE);
		String value = preference.getString(key, "");
		return value;
	}

	/**
	 * 获取当前时间
	 * 
	 * @return 当前时间字符串 格式(dd/MM/yyyy HH:mm:ss)
	 */
	public static String getCurFormatDate() {
		return mFormat.format(new Date());
	}

	/**
	 * 正常返回manifest中的meta-data为channel的value 若没有或为空，则返回null
	 * 
	 * @param context
	 *            packageName包名
	 * @return
	 */
	// public static String getChannel(Context context, String packageName,
	// String channelKey) {
	// ApplicationInfo ai;
	// try {
	// ai = context.getPackageManager().getApplicationInfo(
	// packageName, PackageManager.GET_META_DATA);
	// Bundle bundle = ai.metaData;
	// //Integer param = bundle.getInt(channelKey);
	// Object param = bundle.get(channelKey);
	// if(param.getClass() == Integer.class){
	// return ((Integer)param).toString();
	// }else{
	// return param.toString();
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return null;
	// }
	public static String getChannel(Context context, String channelKey) {
		ApplicationInfo ai;
		try {
			ai = context.getPackageManager().getApplicationInfo(
					context.getPackageName(), PackageManager.GET_META_DATA);
			Bundle bundle = ai.metaData;
			// Integer param = bundle.getInt(channelKey);
			Object param = bundle.get(channelKey);
			if (param.getClass() == Integer.class) {
				return ((Integer) param).toString();
			} else {
				return param.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
